{% extends "layouts/base.html" %}

{% block title %}医生交流管理 - 近视预防干预系统{% endblock %}

{% block content %}
<main class="main-content-container">
  <div class="doctor-consultation-content">
    <div class="page-header">
      <h1><i class="bi bi-chat-left-dots"></i> 医生交流管理中心</h1>
      <p class="text-muted">管理用户咨询、医生回复和专业交流</p>
    </div>

    <!-- 筛选器 -->
    <div class="card mb-4">
      <div class="card-body">
        <div class="row g-3">
          <div class="col-md-3">
            <div class="input-group">
              <span class="input-group-text"><i class="bi bi-search"></i></span>
              <input type="text" class="form-control" id="searchInput" placeholder="搜索咨询内容...">
            </div>
          </div>
          <div class="col-md-2">
            <select class="form-select" id="statusFilter">
              <option value="">全部状态</option>
              <option value="pending">待回复</option>
              <option value="replied">已回复</option>
              <option value="closed">已关闭</option>
            </select>
          </div>
          <div class="col-md-2">
            <select class="form-select" id="categoryFilter">
              <option value="">全部分类</option>
              <option value="vision">视力咨询</option>
              <option value="intervention">干预方法</option>
              <option value="treatment">治疗建议</option>
              <option value="prevention">预防措施</option>
              <option value="other">其他</option>
            </select>
          </div>
          <div class="col-md-2">
            <select class="form-select" id="doctorFilter">
              <option value="">全部医生</option>
              <!-- 动态加载医生列表 -->
            </select>
          </div>
          <div class="col-md-3">
            <div class="btn-group w-100">
              <button class="btn btn-outline-secondary" id="resetFiltersBtn">
                <i class="bi bi-arrow-clockwise"></i> 重置
              </button>
              <button class="btn btn-outline-info" id="exportBtn">
                <i class="bi bi-download"></i> 导出
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 咨询统计 -->
    <div class="row mb-4">
      <div class="col-md-3">
        <div class="card bg-warning text-white">
          <div class="card-body">
            <div class="d-flex align-items-center">
              <i class="bi bi-clock-history fs-2 me-3"></i>
              <div>
                <h5 class="card-title mb-0" id="pendingCount">0</h5>
                <p class="card-text">待回复</p>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="col-md-3">
        <div class="card bg-success text-white">
          <div class="card-body">
            <div class="d-flex align-items-center">
              <i class="bi bi-check-circle fs-2 me-3"></i>
              <div>
                <h5 class="card-title mb-0" id="repliedCount">0</h5>
                <p class="card-text">已回复</p>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="col-md-3">
        <div class="card bg-info text-white">
          <div class="card-body">
            <div class="d-flex align-items-center">
              <i class="bi bi-person-badge fs-2 me-3"></i>
              <div>
                <h5 class="card-title mb-0" id="activeDoctorsCount">0</h5>
                <p class="card-text">活跃医生</p>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="col-md-3">
        <div class="card bg-primary text-white">
          <div class="card-body">
            <div class="d-flex align-items-center">
              <i class="bi bi-graph-up fs-2 me-3"></i>
              <div>
                <h5 class="card-title mb-0" id="todayCount">0</h5>
                <p class="card-text">今日咨询</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 咨询列表 -->
    <div class="card">
      <div class="card-header">
        <h5 class="card-title mb-0">
          <i class="bi bi-list-ul"></i> 咨询列表
        </h5>
      </div>
      <div class="card-body">
        <div class="table-responsive">
          <table class="table table-hover" id="consultationsTable">
            <thead>
              <tr>
                <th>用户</th>
                <th>咨询内容</th>
                <th>分类</th>
                <th>状态</th>
                <th>分配医生</th>
                <th>创建时间</th>
                <th>最后回复</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <!-- 动态加载内容 -->
            </tbody>
          </table>
        </div>
        
        <!-- 分页器 -->
        <nav aria-label="咨询分页" class="mt-3">
          <ul class="pagination justify-content-center" id="pagination">
            <!-- 动态生成分页 -->
          </ul>
        </nav>
      </div>
    </div>
  </div>
</main>

<!-- 咨询详情模态框 -->
<div class="modal fade" id="consultationDetailModal" tabindex="-1">
  <div class="modal-dialog modal-xl">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">咨询详情</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div id="consultationDetailContent">
          <!-- 动态加载内容 -->
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
      </div>
    </div>
  </div>
</div>

<!-- 医生回复模态框 -->
<div class="modal fade" id="replyModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">医生回复</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <form id="replyForm">
          <div class="mb-3">
            <label for="replyContent" class="form-label">回复内容</label>
            <textarea class="form-control" id="replyContent" rows="6" required placeholder="请输入专业的医疗建议..."></textarea>
          </div>
          <div class="row">
            <div class="col-md-6">
              <div class="mb-3">
                <label for="replyCategory" class="form-label">回复分类</label>
                <select class="form-select" id="replyCategory">
                  <option value="diagnosis">诊断建议</option>
                  <option value="treatment">治疗方案</option>
                  <option value="prevention">预防措施</option>
                  <option value="lifestyle">生活建议</option>
                  <option value="follow_up">随访安排</option>
                </select>
              </div>
            </div>
            <div class="col-md-6">
              <div class="mb-3">
                <label for="priority" class="form-label">紧急程度</label>
                <select class="form-select" id="priority">
                  <option value="normal">普通</option>
                  <option value="urgent">紧急</option>
                  <option value="emergency">急诊</option>
                </select>
              </div>
            </div>
          </div>
          <div class="mb-3">
            <label for="recommendations" class="form-label">具体建议</label>
            <textarea class="form-control" id="recommendations" rows="3" placeholder="如需复查、用药建议、生活注意事项等..."></textarea>
          </div>
          <div class="mb-3">
            <div class="form-check">
              <input class="form-check-input" type="checkbox" id="requireFollowUp">
              <label class="form-check-label" for="requireFollowUp">
                需要安排随访
              </label>
            </div>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
        <button type="button" class="btn btn-success" id="sendReplyBtn">发送回复</button>
      </div>
    </div>
  </div>
</div>

<!-- 分配医生模态框 -->
<div class="modal fade" id="assignModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">分配医生</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <form id="assignForm">
          <div class="mb-3">
            <label for="assignedDoctor" class="form-label">选择医生</label>
            <select class="form-select" id="assignedDoctor" required>
              <option value="">请选择医生</option>
              <!-- 动态加载医生列表 -->
            </select>
          </div>
          <div class="mb-3">
            <label for="assignNote" class="form-label">分配说明</label>
            <textarea class="form-control" id="assignNote" rows="3" placeholder="可选：说明分配原因或特殊要求..."></textarea>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" id="confirmAssignBtn">确认分配</button>
      </div>
    </div>
  </div>
</div>

<script>
let currentConsultationId = null;

document.addEventListener('DOMContentLoaded', function() {
    // 初始化页面
    loadConsultations();
    loadConsultationStats();
    loadDoctors();
    
    // 绑定事件
    document.getElementById('searchInput').addEventListener('input', debounce(searchConsultations, 300));
    document.getElementById('statusFilter').addEventListener('change', searchConsultations);
    document.getElementById('categoryFilter').addEventListener('change', searchConsultations);
    document.getElementById('doctorFilter').addEventListener('change', searchConsultations);
    document.getElementById('resetFiltersBtn').addEventListener('click', resetFilters);
    document.getElementById('sendReplyBtn').addEventListener('click', sendReply);
    document.getElementById('confirmAssignBtn').addEventListener('click', confirmAssign);
});

// 加载咨询列表
function loadConsultations(page = 1) {
    const searchTerm = document.getElementById('searchInput').value;
    const statusFilter = document.getElementById('statusFilter').value;
    const categoryFilter = document.getElementById('categoryFilter').value;
    const doctorFilter = document.getElementById('doctorFilter').value;
    
    const params = new URLSearchParams({
        page: page,
        search: searchTerm,
        status: statusFilter,
        category: categoryFilter,
        doctor: doctorFilter
    });
    
    AuthManager.authenticatedFetch(`/api/admin/consultations?${params}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderConsultationsTable(data.data.consultations);
                renderPagination(data.data.pagination);
            } else {
                showAlert('加载咨询列表失败: ' + data.message, 'danger');
            }
        })
        .catch(error => {
            showAlert('网络错误，请重试', 'danger');
            console.error('Error:', error);
        });
}

// 加载咨询统计
function loadConsultationStats() {
    AuthManager.authenticatedFetch('/api/admin/consultations/stats')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById('pendingCount').textContent = data.data.pending || 0;
                document.getElementById('repliedCount').textContent = data.data.replied || 0;
                document.getElementById('activeDoctorsCount').textContent = data.data.active_doctors || 0;
                document.getElementById('todayCount').textContent = data.data.today || 0;
            }
        })
        .catch(error => {
            console.error('Error loading stats:', error);
        });
}

// 加载医生列表
function loadDoctors() {
    AuthManager.authenticatedFetch('/api/admin/doctors')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const doctorFilter = document.getElementById('doctorFilter');
                const assignedDoctor = document.getElementById('assignedDoctor');
                
                // 清空现有选项（保留第一个默认选项）
                while (doctorFilter.children.length > 1) {
                    doctorFilter.removeChild(doctorFilter.lastChild);
                }
                while (assignedDoctor.children.length > 1) {
                    assignedDoctor.removeChild(assignedDoctor.lastChild);
                }
                
                // 添加医生选项
                data.data.forEach(doctor => {
                    const option1 = document.createElement('option');
                    option1.value = doctor.id;
                    option1.textContent = doctor.name;
                    doctorFilter.appendChild(option1);
                    
                    const option2 = document.createElement('option');
                    option2.value = doctor.id;
                    option2.textContent = `${doctor.name} (${doctor.specialty || '全科'})`;
                    assignedDoctor.appendChild(option2);
                });
            }
        })
        .catch(error => {
            console.error('Error loading doctors:', error);
        });
}

// 渲染咨询表格
function renderConsultationsTable(consultations) {
    const tbody = document.querySelector('#consultationsTable tbody');
    tbody.innerHTML = '';
    
    consultations.forEach(consultation => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${consultation.user_name || '匿名用户'}</td>
            <td>
                <div class="consultation-content">
                    ${consultation.content.length > 60 ? consultation.content.substring(0, 60) + '...' : consultation.content}
                </div>
            </td>
            <td>
                <span class="badge bg-info">${getCategoryText(consultation.category)}</span>
            </td>
            <td>
                <span class="badge bg-${getStatusColor(consultation.status)}">${getStatusText(consultation.status)}</span>
            </td>
            <td>${consultation.doctor_name || '未分配'}</td>
            <td>${formatDate(consultation.created_at)}</td>
            <td>${consultation.last_reply_at ? formatDate(consultation.last_reply_at) : '-'}</td>
            <td>
                <div class="btn-group btn-group-sm">
                    <button class="btn btn-outline-primary" onclick="viewConsultation(${consultation.id})" title="查看详情">
                        <i class="bi bi-eye"></i>
                    </button>
                    <button class="btn btn-outline-success" onclick="replyConsultation(${consultation.id})" title="回复">
                        <i class="bi bi-reply"></i>
                    </button>
                    <button class="btn btn-outline-warning" onclick="assignDoctor(${consultation.id})" title="分配医生">
                        <i class="bi bi-person-plus"></i>
                    </button>
                </div>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// 工具函数
function getCategoryText(category) {
    const categories = {
        'vision': '视力咨询',
        'intervention': '干预方法',
        'treatment': '治疗建议',
        'prevention': '预防措施',
        'other': '其他'
    };
    return categories[category] || category;
}

function getStatusText(status) {
    const statuses = {
        'pending': '待回复',
        'replied': '已回复',
        'closed': '已关闭'
    };
    return statuses[status] || status;
}

function getStatusColor(status) {
    const colors = {
        'pending': 'warning',
        'replied': 'success',
        'closed': 'secondary'
    };
    return colors[status] || 'secondary';
}

function viewConsultation(consultationId) {
    AuthManager.authenticatedFetch(`/api/admin/consultations/${consultationId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const consultation = data.data;
                document.getElementById('consultationDetailContent').innerHTML = `
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <strong>用户：</strong> ${consultation.user_name || '匿名用户'}
                            </div>
                            <div class="mb-3">
                                <strong>分类：</strong> ${getCategoryText(consultation.category)}
                            </div>
                            <div class="mb-3">
                                <strong>状态：</strong> ${getStatusText(consultation.status)}
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <strong>分配医生：</strong> ${consultation.doctor_name || '未分配'}
                            </div>
                            <div class="mb-3">
                                <strong>创建时间：</strong> ${formatDate(consultation.created_at)}
                            </div>
                            <div class="mb-3">
                                <strong>最后回复：</strong> ${consultation.last_reply_at ? formatDate(consultation.last_reply_at) : '暂无回复'}
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <strong>咨询内容：</strong>
                        <div class="p-3 bg-light rounded">${consultation.content}</div>
                    </div>
                    ${consultation.replies && consultation.replies.length > 0 ? `
                        <div class="mb-3">
                            <strong>回复记录：</strong>
                            ${consultation.replies.map(reply => `
                                <div class="mt-2 p-3 bg-success bg-opacity-10 rounded">
                                    <div class="mb-1">
                                        <strong>${reply.doctor_name}</strong> - ${formatDate(reply.created_at)}
                                        <span class="badge bg-info ms-2">${reply.category || '普通回复'}</span>
                                    </div>
                                    <div class="mb-2">${reply.content}</div>
                                    ${reply.recommendations ? `<div class="text-muted"><strong>建议：</strong> ${reply.recommendations}</div>` : ''}
                                </div>
                            `).join('')}
                        </div>
                    ` : ''}
                `;
                new bootstrap.Modal(document.getElementById('consultationDetailModal')).show();
            } else {
                showAlert('加载咨询详情失败', 'danger');
            }
        })
        .catch(error => {
            showAlert('网络错误，请重试', 'danger');
            console.error('Error:', error);
        });
}

function replyConsultation(consultationId) {
    currentConsultationId = consultationId;
    document.getElementById('replyForm').reset();
    new bootstrap.Modal(document.getElementById('replyModal')).show();
}

function assignDoctor(consultationId) {
    currentConsultationId = consultationId;
    document.getElementById('assignForm').reset();
    new bootstrap.Modal(document.getElementById('assignModal')).show();
}

function sendReply() {
    if (!currentConsultationId) return;
    
    const replyData = {
        reply_content: document.getElementById('replyContent').value,
        category: document.getElementById('replyCategory').value,
        priority: document.getElementById('priority').value,
        recommendations: document.getElementById('recommendations').value,
        require_follow_up: document.getElementById('requireFollowUp').checked
    };
    
    AuthManager.authenticatedFetch(`/api/admin/consultations/${currentConsultationId}/reply`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(replyData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('回复发送成功', 'success');
            bootstrap.Modal.getInstance(document.getElementById('replyModal')).hide();
            loadConsultations();
            loadConsultationStats();
        } else {
            showAlert('发送失败: ' + data.message, 'danger');
        }
    })
    .catch(error => {
        showAlert('网络错误，请重试', 'danger');
        console.error('Error:', error);
    });
}

function confirmAssign() {
    if (!currentConsultationId) return;
    
    const assignData = {
        doctor_id: document.getElementById('assignedDoctor').value,
        note: document.getElementById('assignNote').value
    };
    
    AuthManager.authenticatedFetch(`/api/admin/consultations/${currentConsultationId}/assign`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(assignData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('医生分配成功', 'success');
            bootstrap.Modal.getInstance(document.getElementById('assignModal')).hide();
            loadConsultations();
        } else {
            showAlert('分配失败: ' + data.message, 'danger');
        }
    })
    .catch(error => {
        showAlert('网络错误，请重试', 'danger');
        console.error('Error:', error);
    });
}

function resetFilters() {
    document.getElementById('searchInput').value = '';
    document.getElementById('statusFilter').value = '';
    document.getElementById('categoryFilter').value = '';
    document.getElementById('doctorFilter').value = '';
    loadConsultations(1);
}

function searchConsultations() {
    loadConsultations(1);
}

// 其他工具函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

function formatDate(dateString) {
    return new Date(dateString).toLocaleDateString('zh-CN');
}

function showAlert(message, type) {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    document.querySelector('.main-content-container').insertBefore(alertDiv, document.querySelector('.main-content-container').firstChild);
    
    setTimeout(() => {
        alertDiv.remove();
    }, 5000);
}
</script>
{% endblock %}

